from common.libs.Helper import getCurrentDate
from common.models.member import MemberAddress
from web.controllers.api import route_api
from flask import request, g
from flask import jsonify

@route_api.route('/my/address/set', methods=['POST'])
def myAddressSet():
    """
    地址的增加和修改
    :return:
    """
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    resp = request.values
    id = resp['id'] if 'id' in resp and resp['id'] else 0
    city_id = resp['city_id'] if 'city_id' in resp and resp['city_id'] else 0
    province_id = resp['province_id'] if 'province_id' in resp and resp['province_id'] else 0
    district_id = resp['district_id'] if 'district_id' in resp and resp['district_id'] else 0
    nickname = resp.get('nickname')
    mobile = resp.get('mobile')
    province = resp.get('province')
    city = resp.get('city')
    district = resp.get('district')
    address = resp.get('address')

    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入'
        return jsonify(result)

    if not nickname:
        result['code'] = -1
        result['msg'] = '请输入姓名'
        return jsonify(result)

    if not province or not city:
        result['code'] = -1
        result['msg'] = '请选择省份和地区'
        return jsonify(result)

    if not mobile:
        result['code'] = -1
        result['msg'] = '请输入手机号'
        return jsonify(result)

    if not address:
        result['code'] = -1
        result['msg'] = '请输入详细地址'
        return jsonify(result)

    address_info = MemberAddress.query.filter_by(id=id, member_id=current_member.id).first()
    if address_info:
        model_address = address_info
    else:
        is_has_default = MemberAddress.query.filter_by(is_default=1, status=1, member_id=current_member.id).count()
        model_address = MemberAddress()
        model_address.member_id = current_member.id
        model_address.status = 1
        model_address.is_default = 1 if is_has_default == 0 else 0
        model_address.created_time = getCurrentDate()

    model_address.nickname = nickname
    model_address.mobile = mobile
    model_address.province_id = province_id
    model_address.province_str = province
    model_address.city_id = city_id
    model_address.city_str = city
    model_address.area_id = district_id
    model_address.area_str = district
    model_address.address = address
    model_address.updated_time = getCurrentDate()
    model_address.save()

    return jsonify(result)

@route_api.route('/my/address')
def myAddress():
    """
    地址列表的展示
    :return:
    """
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    addressList = []
    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入'
        return jsonify(result)
    address_list = MemberAddress.query.filter_by(member_id=current_member.id).all()
    for address in address_list:
        address_detail = address.province_str + address.city_str + address.area_str + address.address
        res = {
            'id': address.id,
            'name': address.nickname,
            'mobile': address.mobile,
            'address': address_detail,
            'isDefault': address.is_default
        }
        addressList.append(res)
    result['data']['addressList'] = addressList
    return jsonify(result)

@route_api.route('/my/address/info')
def myAddressInfo():
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    id = request.values.get('id')
    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入'
        return jsonify(result)
    address_info = MemberAddress.query.filter_by(id=id, member_id=current_member.id).first()
    if not address_info:
        result['code'] = -1
        result['msg'] = '业务繁忙，请稍后再试！'
        return jsonify(result)
    info = {
        'nickname': address_info.nickname,
        'mobile': address_info.mobile,
        'province_str': address_info.province_str,
        'city_str': address_info.city_str,
        'area_str': address_info.area_str,
        'address': address_info.address,
    }
    result['data']['info'] = info
    return jsonify(result)

@route_api.route('/my/address/ops', methods=['POST'])
def myAddressDel():
    result = {'code': 200, 'msg': '操作成功', 'data': {}}
    id = request.values.get('id')
    act = request.values.get('act')
    current_member = g.current_member
    if not current_member:
        result['code'] = -1
        result['msg'] = '请先登入'
        return jsonify(result)
    address_info = MemberAddress.query.filter_by(member_id=current_member.id, id=id).first()
    if not address_info:
        result['code'] = -1
        result['msg'] = '业务繁忙，请稍后再试！'
        return jsonify(result)
    # 查询是否有额外地址
    if act == 'del':
        extra_address = MemberAddress.query.filter(~MemberAddress.id.in_([id])).all()
        # 如果删除的是默认地址，则设置下个地址为默认地址
        if address_info.is_default == 1 and len(extra_address) > 0:
            extra_address[0].is_default = 1
            extra_address[0].updated_time = getCurrentDate()
            extra_address[0].update()
        address_info.delete()
    if act == 'default':
        # 先取消所有默认地址
        MemberAddress.query.filter_by(member_id=current_member.id).update({ 'is_default':0})
        address_info.is_default = 1
        address_info.updated_time = getCurrentDate()
        address_info.update()
    return jsonify(result)
